<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\library\Weixin;
use app\common\model\Commission;
use app\common\model\Order as OrderModel;
use think\Db;
use think\Exception;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
	protected $relationSearch = true;
    
    /**
     * Order模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OrderModel;
		$list = [
			'statusList' => OrderModel::$statusList,
			'payStatusList' => OrderModel::$payStatusList,
			'shippingStatusList' => OrderModel::$shippingStatusList,
			'areaList' => User::$areaList,
			'typeList' => OrderModel::$typeList,
			'signTypeList' => OrderModel::$signTypeList,
			'rebateList' => OrderModel::$rebateList
		];
		
		$this->assignconfig($list);
		$this->assign($list);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
	
	/**
	 * 查看
	 */
	public function index()
	{
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
			$with = ['user', 'destruct', 'recommend', 'shop', 'warehouse', 'center', 'theater'];
			
			$total = $this->model
				->with($with)
				->where($where)
				->order($sort, $order)
				->count();
			
			$list = $this->model
				->with($with)
				->where($where)
				->order($sort, $order)
				->limit($offset, $limit)
				->select();
			
			$list = collection($list)->toArray();
			$result = array("total" => $total, "rows" => $list);
			
			return json($result);
		}
		return $this->view->fetch();
	}
	
	/**
	 * 支付完成
	 * @param $ids
	 */
	public function paySuccess($ids) {
		$res = $this->model->paySuccess($ids);
		if($res) {
			$this->success('操作成功');
		} else {
			$this->error('操作出错'.$this->model->getError());
		}
	}
	
	
	/**
	 * 发货
	 */
	public function ship($ids) {
		$row = $this->model->with('user')->find($ids);
		!$row && $this->error('订单不存在');
		
		if($row['status'] != OrderModel::STATUS_WAIT_SHIPPING) {
			$this->error('非待发货订单');
		}
		
			
			$this->model->startTrans();
			try {
				
				$orderRes = $this->model->save([
					'status' => OrderModel::STATUS_WAIT_SIGN,
					'shipping_status' => OrderModel::SHIPPING_STATUS_WAIT,
					'shipping_time' => time(),
				], ['id' => $ids]);
				if(!$orderRes) {
					throw new Exception('更改订单状态出错');
				}
				
				$this->model->commit();
				$this->success('操作成功');
			} catch (Exception $e) {
				$this->model->rollback();
				$this->error($e->getMessage());
			}
			
	}
	
	
	/**
	 * 物流
	 */
	public function shipping($ids){
		$row = $this->model->find($ids);
		!$row && $this->error('订单不存在');
		
		if($row['shipping_status'] === null) {
			$this->error('非已发货订单');
		}
		
		$model = new \app\common\model\OrderShipping();
		$res = $model->getShipping($ids);
		if(!isset($res['Traces'])) {
			$this->error('没有物流信息');
		}
		return $this->view->fetch('shipping', [
			'res' => $res]);
	}

	public function detail($ids) {
		$order = $this->model->find($ids);
		$where['g.order_id'] = $ids;
		$goods = Db::name('orderGoods')->alias('g')
			->join('user u', 'g.recommend_user_id = u.id', 'left')
			->where($where)
			->field('g.*, u.nickname')
			->select();
		
		if($goods) {
			foreach ($goods as &$good) {
				$good['goods_info'] = json_decode($good['goods_info'], true);
			}
		}
		
		$address = Db::name('orderAddress')->alias('a')
			->join('area p', 'a.province_id = p.id', 'left')
			->join('area c', 'a.city_id = c.id', 'left')
			->join('area aa', 'a.area_id = aa.id', 'left')
			->where(['a.order_id' => $ids])
			->field('a.id, a.name, a.mobile, a.province_id, a.city_id, a.area_id, a.address, p.name as province, c.name as city, aa.name as area')
			->find();
		
		return $this->view->fetch('detail', [
			'order' => $order,
			'goods' => $goods,
			'address' => $address
		]);
	}
	
	/**
	 * 订单完成
	 */
	public function done($ids){
		$row = $this->model->find($ids);
		!$row && $this->error('订单不存在');
		
		if($row['status'] != OrderModel::STATUS_SIGN && $row['status'] != OrderModel::STATUS_WAIT_SIGN) {
			$this->error('非待核销或待签收订单');
		}
		
		$this->model->startTrans();
		try {
			$res = $this->model->save(['status' => OrderModel::STATUS_SUCCESS], ['id' => $ids]);
			if(!$res) {
				throw new Exception('更改订单状态成功');
			}
			
			//更改返利状态
			//订单状态为待结算且全部商品已核销完后更改佣金状态为已结算
			if($row['rebate_status'] == \app\common\model\Order::REBATE_WAIT) {
				$commissionModel = new Commission();
				$commissionRes = $commissionModel->send($row['id']);
				if(!$commissionRes) {
					throw new Exception('更改返利记录状态出错');
				}
			}
			$this->model->commit();
			$this->success('操作成功');
		} catch (Exception $e) {
			$this->model->rollback();
			$this->error($e->getMessage());
		}

	}
	
		
		
		/**
	 * 物流
	 */
	public function refund($ids){
		$order = $this->model->find($ids);
		!$order && $this->error('订单不存在');
		
		if($order['pay_status'] != OrderModel::PAY_STATUS_REFUND_FAIL) {
			$this->error('非退款失败订单');
		}
		
		$config = config('weixin');
		$weixin = new Weixin($config['smallapp']['app_id']);
		$refundNo = time().mt_rand(100000, 999999);
		$res = $weixin->refund($order['transaction_no'], $refundNo, $order['amount'],$order['amount'], '拼团失败退款');
		
		if(!$res) {
			$this->error('退款失败，请检查微信商户平台余额是否充足');
		}
		
		$payRes = Db::name('order')->where('id', $order['id'])->update(['pay_status' => OrderModel::PAY_STATUS_REFUND]);
		if($payRes) {
			$this->error('退款成功');
		}
		
		$this->error('退款出错');
	}
}
